<template>
  <n-card :bordered="false" size="small">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
  </n-card>
  <n-card :bordered="false" class="mt-2" size="small">
    <BasicTable
      :columns="tableColumns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="tableRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>
    </BasicTable>
    <n-drawer v-model:show="showModal" :mask-closable="false" width="40%">
      <n-drawer-content :title="dialogTitle + pageTitle" :closable="true">
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          class="py-4"
        >
          <slot name="form"></slot>
        </n-form>
        <template #footer>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { http } from '@/utils/http/axios';
  import { PlusOutlined } from '@vicons/antd';
  import { useRouter } from 'vue-router';
  import { FormRules } from 'naive-ui';

  const props = defineProps({
    searchSchemas: Object as PropType<Array<FormSchema>>,
    tableColumns: Array,
    pageTitle: {
      type: String,
      default: '',
    },
    formParams: Object,
    rules: Object as PropType<FormRules>,
    actionWidth: {
      type: Number,
      default: 120,
    },
    action: {
      type: Array,
      default: () => [
        { label: '删除', type: 'error', event: 'delete' },
        { label: '编辑', type: 'primary', event: 'edit' },
      ],
    },
    url: Object as any,
  });

  const emits = defineEmits(['edit']);

  const dialogTitle = ref('新建');

  const router = useRouter();
  const formRef: any = ref(null);
  const tableRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);

  const actionColumn = reactive({
    width: props.actionWidth,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      let action = new Array<any>();
      props.action?.forEach((item) => {
        if (item) {
          let v = item as any;
          if (v.event === 'delete') {
            v.onClick = handleDelete.bind(null, record);
          } else if (v.event === 'edit') {
            v.onClick = handleEdit.bind(null, record);
          }
          action.push(v);
        }
      });
      return h(TableAction as any, {
        style: 'button',
        actions: action,
      });
    },
  });

  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:2 m:3 l:4 xl:4 2xl:4' },
    labelWidth: '',
    schemas: props.searchSchemas,
  });

  function addTable() {
    showModal.value = true;
    dialogTitle.value = '新建';
  }

  const loadDataTable = async (res) => {
    // return await http.request({
    //   url: props.url.list,
    //   method: 'post',
    //   data: { ...getFieldsValue(), ...res },
    // });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    tableRef.value.reload();
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        window['$message'].success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    showModal.value = true;
    dialogTitle.value = '编辑';
    emits('edit', record);
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    window['$message'].info('点击了删除');
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
</script>
